<template>
    <div class="app-container calendar-list-container">
        <!-- 查询条件 -->
        <div class="filter-container">
            <div class="filter-li">
                <label>拜访时间</label>
                <el-date-picker size="small" v-model="listQuery.time" type="daterange" placeholder="选择日期范围">
                </el-date-picker>
            </div>
            <div class="filter-li">
                <label>客户单位</label>
                <el-select  size="small"  v-model="listQuery.customer_id" placeholder="请选择" clearable>
                    <el-option v-for="item in customers" :key="item.id" :label="item.dept" :value="item.id">
                    </el-option>
                </el-select>
            </div>
            <div class="filter-li">
                <label>业务员</label>
                <el-select  size="small"  v-model="listQuery.userid" placeholder="请选择" clearable>
                    <el-option v-for="item in users" :key="item.userid" :label="item.name" :value="item.userid">
                    </el-option>
                </el-select>
            </div>
            <br/>
            <el-button  size="small"  class="filter-item" type="primary" v-waves icon="search" @click="onFilter">搜索</el-button>
            <el-button  size="small"  class="filter-item" type="success" v-waves icon="edit" @click="add()">新增客户拜访</el-button>
            <el-button  size="small"  class="filter-item" type="success" v-waves icon="edit" @click="exportXls()">导出Excel</el-button>
        </div>

        <!-- 列表 -->
        <el-table  size="small"  :data="list" v-loading="listLoading" element-loading-text="加载中，请稍后" border fit highlight-current-row style="width: 100%"
            @current-change="onRowSelect">

            <el-table-column type="index" width="80">
            </el-table-column>

            <el-table-column align="center" label="客户单位">
                <template scope="scope">
                    <span>{{scope.row.customer.dept}}</span>
                </template>
            </el-table-column>

            <el-table-column align="center" label="联系人">
                <template scope="scope">
                    <span>{{scope.row.contact.name }}</span>
                </template>
            </el-table-column>

            <el-table-column align="center" label="业务员">
                <template scope="scope">
                    <span>{{scope.row.user.name}}</span>
                </template>
            </el-table-column>

            <el-table-column align="center" label="拜访时间">
                <template scope="scope">
                    <span>{{ scope.row.visit_time | time_format('YYYY-MM-DD') }}</span>
                </template>
            </el-table-column>

            <el-table-column align="left" label="行动计划">
                <template scope="scope">
                    <span>{{ scope.row.plan }}</span>
                </template>
            </el-table-column>

            <el-table-column align="left" label="反馈">
                <template scope="scope">
                    <span>{{ scope.row.reply }}</span>
                </template>
            </el-table-column>

            <el-table-column align="center" label="点评">
                <template scope="scope">
                    <span>{{ scope.row.remark }}</span>
                </template>
            </el-table-column>

            <el-table-column align="center" label="操作" width="180">
                <template scope="scope">
                    <!-- <el-button size="small" type="success" @click="edit(scope.row)">编辑</el-button> -->
                    <el-button size="small" type="success" @click="edit(scope.row, true)">点评</el-button>
                    <el-button size="small" type="danger" @click="remove(scope.row)">删除</el-button>
                </template>
            </el-table-column>

        </el-table>

        <div v-show="!listLoading" class="pagination-container">
            <el-pagination @size-change="onSizeChange" @current-change="onCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]"
                :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>

        <!-- 表单 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
            <el-form ref="appForm" :rules="rules" class="small-space" :model="form" label-position="left" label-width="130px">

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="客户单位" prop="customer_id">
                            <el-select :disabled="!canEdit" v-model="form.customer_id" placeholder="请选择" @change="onCustomerChange">
                                <el-option v-for="item in customers" :key="item.id" :label="item.dept" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系人" prop="contact_id">
                            <el-select :disabled="show_mark" v-model="form.contact_id" placeholder="请选择">
                                <el-option v-for="item in contact" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="业务员" prop="userid">
                    <el-select :disabled="show_mark" v-model="form.userid" placeholder="请选择">
                        <el-option v-for="item in users" :key="item.userid" :label="item.name" :value="item.userid">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="拜访时间" prop="visit_time">
                            <el-date-picker :disabled="show_mark" v-model="form.visit_time" type="date" placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="下次回访时间" prop="next_time">
                            <el-date-picker :disabled="show_mark" v-model="form.next_time" type="date" placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="行动反馈" prop="reply">
                    <el-input :disabled="show_mark" type="textarea" v-model="form.reply"></el-input>
                </el-form-item>

                <el-form-item label="行动计划" prop="plan">
                    <el-input :disabled="show_mark" type="textarea" v-model="form.plan"></el-input>
                </el-form-item>

                <el-form-item label="拜访费用" prop="fee">
                    <el-table :data="form.visit_fees" border fit highlight-current-row max-height="250" show-summary :summary-method="sumFee">
                        <el-table-column align="center" label="费用">
                            <template scope="scope">
                                <span> {{ scope.row.fee_name }} </span>
                            </template>
                        </el-table-column>

                        <el-table-column align="center" label="金额">
                            <template scope="scope">
                                <el-input :disabled="show_mark" type="number" v-model="scope.row.fee" @change="sumFee"></el-input>
                            </template>
                        </el-table-column>
                    </el-table>

                </el-form-item>

                <el-form-item label="点评" v-show="show_mark">
                    <el-input type="textarea" v-model="form.remark"></el-input>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import api from '@/api/visit'
    import customerApi from '@/api/customer'
    import userApi from '@/api/user'
    import waves from '@/directive/waves/index.js' // 水波纹指令
    import { mapGetters, mapState } from 'vuex'
    import _ from 'lodash'
    import { clearObject } from '@/utils/object.js'

    export default {
        name: 'visit',
        directives: {
            waves
        },
        data() {
            return {
                list: null,
                total: null,
                listLoading: false,
                listQuery: {
                    page: 1,
                    limit: 20,
                    time: '',
                    customer_id: null,
                    userid: null,
                },
                dialogTitle: null,
                dialogFormVisible: false,
                form: {
                    id: null,
                    customer_id: null,
                    contact_id: null,
                    userid: null,
                    visit_time: null,
                    next_time: null,
                    reply: null,
                    plan: null,
                    fee: null,
                    visit_fees: []
                },
                row: null, //当前选中行
                rules: {
                    customer_id: [{ required: true, message: '不能为空', trigger: 'blur' }],
                    userid: [{ required: true, message: '不能为空', trigger: 'blur' }],
                    visit_time: [{ type: 'date', required: true, message: '不能为空', trigger: 'blur' }],
                    next_time: [{ type: 'date', required: true, message: '不能为空', trigger: 'blur' }],
                    reply: [{ required: true, message: '不能为空', trigger: 'blur' },
                    { min: 50, message: '至少输入50个字符', trigger: 'blur' }],
                    plan: [{ required: true, message: '不能为空', trigger: 'blur' },
                    { min: 50, message: '至少输入50个字符', trigger: 'blur' }],
                },
                users: [],//用户列表
                customers: [], //客户列表
                show_mark: false,//是否显示点评
            }
        },
        computed: {
            ...mapState({
                contact: state => state.contact.rows,
            }),
            ...mapGetters([
                'dicArray'
            ]),
            canEdit() {
                return !this.show_mark
            }
        },
        async created() {
            await this.$store.dispatch('loadDic')
            await this.getUsers()
            await this.getCustomer()
            await this.getList()
        },
        methods: {
            async getList() {
                this.listLoading = true
                let where = {
                    user_where: {
                        userid: this.listQuery.userid,
                    },
                    customer_where: {
                        id: this.listQuery.customer_id,
                    },
                    visit_where: {
                        visit_time: {
                            $gt: this.listQuery.time ? this.listQuery.time[0] : undefined,
                            $lt: this.listQuery.time ? this.listQuery.time[1] : undefined,
                        }
                    },
                }
                let response = await api.page({
                    page: this.listQuery.page,
                    limit: this.listQuery.limit,
                    where,
                    order: [['customer_id', 'asc'], ['created_at', 'desc']]
                })
                this.listLoading = false
                this.list = response.data.rows
                this.total = response.data.count
            },
            onFilter() {
                this.listQuery.page = 1
                this.getList()
            },
            onRowSelect(val) {
                this.row = val
            },
            onSizeChange(val) {
                this.listQuery.limit = val
                this.getList()
            },
            onCurrentChange(val) {
                this.listQuery.page = val
                this.getList()
            },
            add() {
                this.dialogFormVisible = true
                this.dialogTitle = '新增客户拜访'
                this.show_mark = false
                clearObject(this.form)
                this.form.visit_fees = []
                for (let item of this.dicArray['拜访费用分类']) {
                    this.form.visit_fees.push({ fee_id: item.id, fee: null, fee_name: item.name })
                }
            },
            edit(row, show_mark) {
                this.dialogFormVisible = true
                this.dialogTitle = '编辑客户拜访'
                this.form = row
                //时间格式转换
                this.form.visit_time = new Date(row.visit_time)
                this.form.next_time = new Date(row.next_time)
                //是否显示点评
                this.show_mark = !!show_mark
                this.onCustomerChange()
            },
            save() {
                this.$refs.appForm.validate(async valid => {
                    if (!valid) {
                        return
                    }
                    let ret = await api.save(this.form)
                    if (!ret.success) {
                        return
                    }
                    this.$notify({
                        title: '成功',
                        message: '保存成功',
                        type: 'success',
                        duration: 2000
                    })
                    this.dialogFormVisible = false
                    this.onFilter()
                    clearObject(this.form)
                })
            },
            remove(row) {
                this.$confirm('是否删除该数据?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    let ret = await api.remove(row)
                    if (ret.success) {
                        this.onFilter()
                    }
                })
            },
            //获取客户信息
            async getCustomer() {
                let ret = await customerApi.findAll()
                this.customers = ret.data
            },
            //获取用户信息
            async getUsers() {
                let ret = await userApi.findAll()
                this.users = ret.data
            },
            //客户单位发生改变 重新加载客户联系人
            async onCustomerChange() {
                this.$store.dispatch('contact/page', { customer_id: this.form.customer_id })
            },
            sumFee() {
                var sum = _.sum(_.map(this.form.visit_fees, function (item) { return item.fee == null ? 0 : parseFloat(item.fee) }))
                this.form.fee = sum
                return ['合计', sum]
            },
            exportXls(){
                let columns = [
                    [
                        { header: '序号', key: 'xh', width: 5 },
                        { header: '客户单位', key: 'dept', width: 15 },
                        { header: '联系人', key: 'name', width: 15 },
                        { header: '业务员', key: 'username', width: 15 },
                        { header: '拜访时间', key: 'visit_time', width: 30 },
                        { header: '行动计划', key: 'plan', width: 30 },
                        { header: '反馈', key: 'reply', width: 30 },
                        { header: '点评', key: 'remark', width: 30 }
                    ]
                ]
                let i = 1
                let data = this.list.map(v=>{
                    return {
                        xh: i++,
                        dept: v.customer.dept,
                        name: v.contact.name,
                        username: v.user.name,
                        visit_time: this.time_format(v.visit_time, 'YYYY-MM-DD'),
                        plan: v.plan,
                        reply: v.reply,
                        remark: v.remark,
                    }
                })

                this.download('/api/file/xls', {
                    filename: `拜访记录`,
                    columns: JSON.stringify(columns),
                    data: JSON.stringify(data)
                })
            },
            download(actionUrl, parms) {
                var form = document.createElement("form")
                form.style.display = "none"
                form.action = actionUrl
                form.method = "post"
                document.body.appendChild(form)

                for (var key in parms) {
                    var input = document.createElement("input")
                    input.type = "hidden"
                    input.name = key
                    input.value = parms[key]
                    //input.value = encodeURIComponent(parms[key]);
                    form.appendChild(input)
                }
                form.submit()
            }
        }
    }

</script>
